package com.wx.house.common.config;

import com.wx.house.common.util.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@Configuration
@ConditionalOnProperty(prefix = "common", name = "resttemp", havingValue = "true")
public class RestTemplateConfig {

@Bean
@ConditionalOnMissingBean({RestOperations.class, RestTemplate.class})
public RestOperations restOperations() {
	CloseableHttpClient httpClient = null;
	try {
		httpClient = HttpClientUtils.acceptsUntrustedCertsHttpClient();
	} catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException e) {
		e.printStackTrace();
	}
	assert httpClient != null;
	HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
	RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
	
	List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
	messageConverters.removeIf(converter -> converter instanceof StringHttpMessageConverter);
	messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
	return restTemplate;
}


}
